/**
 * Created by yx on 2017/12/13.
 */
console.log('faceNewsList')

// 初始化table
queryNews();

function queryNews() {
    $("#userNewsList_table").bootstrapTable({
        'url': '/friends/recommandFacePicture/getNewsByPictureId',
        'cache':false,
        //'method': 'post',
        'queryParams':userNewsListParam,
        'toolbar': $('div[data-name="btnCtl"]'),
        'striped': true,
        'pagination': true,
        'sidePagination': 'server',
        'pageSize': globalPageSize,
        'pageList': [],
        'clickToSelect': true,
        'singleSelect': false,
        'smartDisplay': true,
        'responseHandler': function(resb) {
            return {
                'total': resb.data.total,
                'rows': resb.data.content
            }
        },
        'onCheck': function() {
            $("button[data-target='#deleteModal']").removeAttr("disabled");
        },
        'onUncheck': function() {
            console.log($("#userNewsList_table").bootstrapTable("getSelections"));
            if($("#userNewsList_table").bootstrapTable("getSelections").length === 0) {
                $("button[data-target='#deleteModal']").attr("disabled", 'true');
            }
        },
        'columns': [{
            'checkbox': true
            // 'class': 'hide'
        }, {
            'field': 'faceNewsRelationId',
            'align': 'center',
            'valign': 'middle',
            'class': 'hide ID'
        },{
            'title': '序号',
            'align': 'center',
            'formatter': function (value, row, index) {
                return index+1;
            }
        },
        //     {
        //     'field': 'sort',
        //     'title': '排序',
        //     'align': 'center',
        //     'valign': 'middle'
        //     // 'formatter': function (value,row,index) {
        //     //     index+=1;
        //     //     return index
        //     // }
        // },
            {
            'field': 'newsTitle',
            'title': '新闻标题 ',
            'align': 'center',
            'valign': 'middle',
            'formatter': function (value,row,index) {
                return "<a class='newsTitle' data-newsId="+row.newsId+">"+value+"</a>"
            }
        }, {
            'title': '顺序',
            'align': 'center',
            'valign': 'middle',
            'formatter': function (value, row) {
                var html = "<button class='btn btn-sm btn-success glyphicon glyphicon-arrow-up changeSort' data-type='up' style='margin-right: 30px'></button><button class='btn btn-sm btn-success glyphicon glyphicon-arrow-down changeSort' data-type='down'style='margin-right: 30px'></button><button class='btn btn-sm btn-success top'>置顶</button>";
                return html;
            }
        }]
    });
}

function userNewsListParam(params){
    // params["userRecommendType"] = $("#userRecommendType").val();
    params["facePictureId"] = sessionStorage.getItem('facePictureId');
    params['limit'] = params.limit;
    params['offset'] = params.offset;
    return params;
};

//添加新闻模态框显示
$('#addModal').on('show.bs.modal',  function () {
    getNewsList();
});

//新闻搜索
$('#newsSearch').click(function () {
    var queryData = {
        keywords: $('#news_search').val(),
        limit : 50
    };
    // getNewsList();
    $('#newsSearch').attr("disabled",true);
    $('#loading').css('display', 'block');
    newsQuery(queryData);
});

//保存选中的新闻
$('#saveNews').click(function () {
   var newsList = $("#newsList_table").bootstrapTable("getSelections");
   $.ajax({
       type: "POST",
       url: "/friends/recommandFacePicture/addNewsForPictureId?facePictureId="+sessionStorage.getItem('facePictureId'),
       //data: JSON.stringify(queryData),
       data: JSON.stringify(newsList),
       dataType: 'json',
       contentType: 'application/json',
       success: function(resb) {
           console.log(resb.data);
           // if(resb.success) {
           //     alert(resb.data);
           // }
           alert(resb.data);
           $('#addModal').modal('hide');
           $("#userNewsList_table").bootstrapTable('destroy');
           queryNews();
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {
           alert(textStatus);
       }
   })
});

//移除选中的新闻
$('#deleteNews').click(function () {
    var userNewsList = $("#userNewsList_table").bootstrapTable("getSelections");
    console.log(userNewsList);
    var data = [];
    for(var i = 0; i < userNewsList.length; i++) {
        data.push(userNewsList[i].faceNewsRelationId);
    }
    $.ajax({
        type: "POST",
        url: "/friends/recommandFacePicture/deleteNewsForPictureId",
        //data: JSON.stringify(queryData),
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: 'application/json',
        success: function(resb) {
            console.log(resb.data);
            $('#deleteModal').modal('hide');
            $("#userNewsList_table").bootstrapTable('destroy');
            queryNews();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    })
});

//修改顺序
$('#userNewsList_table').on('click', '.changeSort', function () {
    var faceNewsRelationId = $(this).parent().siblings('.ID').html(),
        direction = $(this).attr('data-type');
    var changeSort = {
        faceNewsRelationId: faceNewsRelationId,
        direction: direction
    }
    $.ajax({
        type: "GET",
        url: "/friends/recommandFacePicture/changeRelationSort?faceNewsRelationId=" + faceNewsRelationId + "&direction=" + direction,
        //data: JSON.stringify(queryData),
        // data: JSON.stringify(changeSort),
        dataType: 'json',
        contentType: 'application/json',
        success: function(resb) {
            console.log(resb.data);
            $("#userNewsList_table").bootstrapTable('refresh');
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    })
});

//置顶
$("#userNewsList_table").on('click', '.top', function () {
    var faceNewsRelationId = $(this).parent().siblings('.ID').html();
    $.ajaxSetup({cache:false});
    $.ajax({
        type: "GET",
        url: "/friends/recommandFacePicture/topRelationSort?faceNewsRelationId=" + faceNewsRelationId,
        dataType: 'json',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", sessionStorage.token);
        },
        success: function (resb) {
            if(resb.success) {
                // alert('交换成功');
                $("#userNewsList_table").bootstrapTable("refresh");
            }else{
                alert(resb.message);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
});

//跳转到新闻详情
$('#userNewsList_table').on('click', '.newsTitle', function () {
    var newsId = $(this).attr('data-newsId');
    sessionStorage.setItem('newsId', newsId);
    loadPage('newsDetail/newsDetail.html');
});

$('.row').on('click', '.newsDetail', function () {
    var newsId = $(this).attr('data-newsId');
    // window.open = './detail.html?id='+newsId;
    window.open('../webpage/faceNewsList/detail.html?id='+newsId);
});

//返回上一级页面
$('#back').click(function () {
    loadPage('recommendFace/recommendFace.html');
});

//获取新闻列表
function getNewsList(){
    $("#newsList_table").bootstrapTable('destroy');
    $("#newsList_table").bootstrapTable({
        // 'url': '../serviceType/findAll',
        'url': '/news/posts/findNewsByKeywords',
        'toolbar': $('div[data-name="btnCtl"]'),
        'queryParams': newsQueryParams,
        'cache':false,
        // 'sidePagination': 'server',
        'toolbarAlign': 'right',
        'undefinedText': '-',
        'striped': true,
        'pagination': true,
        'sortable': true, //是否启用排序
        'sortOrder': "asc", //排序方式
        // 'pageSize': globalPageSize,
        'pageList': [],
        'clickToSelect': true,
        'singleSelect': false,
        'smartDisplay': true,
        'ajaxOptions':{
            headers: {"Authorization":sessionStorage.token}
        },
        // 'responseHandler': function (resb) {
        //     console.log(resb.data.content);
        //     return {
        //         'total': resb.data.total,
        //         'rows': resb.data.content
        //     }
        // },
        'columns': [{
            'checkbox': true
            // 'class': 'hide'
        },
            {
                'title': '序号',
                'formatter': function (value, row, index) {
                    return index+1;
                }
            },
            {
                'field': 'postTitle',
                'title': '新闻标题',
                'align': 'center',
                'valign': 'middle',
                'formatter': function (value,row,index) {
                    return "<a class='newsDetail' data-newsId="+row.id+">"+value+"</a>"
                }
            }
        ]
    });
};
//请求服务数据时所传参数
function newsQueryParams(params){
    return {
        keywords: $('#news_search').val(),
        limit : 0
    }
};

// 新闻搜索
function newsQuery(data) {
    $.ajaxSetup({cache:false});
    $.ajax({
        type: "GET",
        url: "/news/posts/findNewsByKeywords?keywords="+data.keywords+"&limit="+data.limit,
        //data: JSON.stringify(queryData),
        // data: data,
        dataType: 'json',
        //contentType: 'application/json',
        success: function(resb) {
            console.log(resb.data);
            $('#newsSearch').removeAttr('disabled');
            $('#loading').css('display', 'none');
            if (resb.data && resb.data.length != 0) {
                $("#newsList_table").bootstrapTable('load',  resb.data);
            } else {
                $("#newsList_table").bootstrapTable('removeAll');
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
    return false;
}
